<template>
    <div class="edu-page-warp">
        <div class="left-part-box">
            <div
                v-for="(menu, index) in menuTreeTypeOpt.data"
                :key="menu.index"
                class="menus-collapse-wrap"
            >
                <el-collapse v-model="menuTreeTypeOpt.value" class="menus-collapse" accordion>
                    <el-collapse-item :title="menu.name" :name="menu.value">
                        <el-tree
                            :data="menuTree[index]"
                            :props="defaultProps"
                            :expand-on-click-node="false"
                            :highlight-current="true"
                            @node-click="nodeClick"
                        >
                        </el-tree>
                    </el-collapse-item>
                </el-collapse>
            </div>
        </div>
        <div class="right-part-box">
            <el-card shadow="never">
                <div class="edu-page-title">
                    {{ menuTreeTypeOpt.data[currentMenuType - 1].name }}操作身份验证明细
                </div>
                <el-row class="bg-white search-bar">
                    <el-col :span="8">
                        <KeywordInput
                            v-model="queryMenuForm.name"
                            placeholder="菜单名称"
                            @enter="queryMenus(true)"
                        />
                    </el-col>
                    <div class="float-right">
                        <el-button type="primary" @click="queryMenus(true)">
                            {{ $t('message.filter') }}
                        </el-button>
                        <!-- 排序暂时隐藏 -->
                        <el-button @click="openOrderDialog">排序</el-button>
                    </div>
                </el-row>
                <el-row>
                    <el-col>
                        <edu-table
                            :data="menus"
                            :total="queryMenuForm.total"
                            :selection="false"
                            :order="false"
                            :max-height="500"
                            @page-change="handleSizeChange"
                            :key="tableKey"
                        >
                            <el-table-column
                                label="菜单中文名称"
                                prop="authNameCh"
                                show-overflow-tooltip
                                min-width="100px"
                            />
                            <el-table-column
                                label="是否激活"
                                show-overflow-tooltip
                                min-width="100px"
                            >
                                <template slot-scope="scope">
                                    <el-tag v-if="scope.row.activeState == 1" type="success">{{activeStatus[scope.row.activeState]}}</el-tag>
                                    <el-tag v-if="scope.row.activeState == 2" type="info">{{activeStatus[scope.row.activeState]}}</el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="用户/组" show-overflow-tooltip>
                                <template slot-scope="scope">
                                    <span v-if="scope.row.boundUser" >{{scope.row.boundUser}}</span>
                                    <el-button v-else type="text" @click="showUserGroup(scope.row.boundGroupId)">
                                        {{ scope.row.boundGroupName }}
                                    </el-button>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="100">
                                <template slot-scope="scope">
                                    <el-button type="text" @click="editMenu(scope.row.authId)">
                                        {{ $t('message.edit') }}
                                    </el-button>
                                </template>
                            </el-table-column>
                        </edu-table>
                    </el-col>
                </el-row>
            </el-card>
        </div>
        <edu-dialog
            ref="editDialog"
            title="编辑操作"
            size="small"
            width="600"
            class="systemDialog"
            @close="closeDialog"
            @confirm="submitConfig"
            
        >
            <el-form
                ref="createMenuForm"
                :model="optionalForm"
                :rules="rules"
                label-suffix="："

            >
                    <el-form-item label="菜单中文名称" label-width="120px" prop="authNameCh">
                        <el-input readonly v-model="createMenuForm.authNameCh" />
                    </el-form-item>
                    <el-form-item label="是否激活"  label-width="120px" prop="activeState">
                        <el-select
                            v-model="optionalForm.activeState"
                            placeholder="请选择"
                            style="width: 100%">
                            <el-option
                                v-for="item in optionalForm.options"
                                :key="item.key"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-row v-if="optionalForm.activeState === 1">
                        <el-col span="10" offset="1">
                            <el-radio class="radio" @change="handleChangeRadio" v-model="optionalForm.radioChecked" :label="1">用户组</el-radio>
                            <el-form-item  prop="phoneNum">
                                 <el-select
                                    v-model="optionalForm.boundGroupId"
                                    :disabled="optionalForm.radioChecked == 2"
                                    placeholder="用户组名称搜索"
                                    style="width:100%"
                                    filterable
                                >
                                    <el-option
                                        v-for="item in userGroups"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col span="10" push="2">
                            <el-radio  class="radio" @change="handleChangeRadio"  v-model="optionalForm.radioChecked" :label="2">用户</el-radio>
                            <el-form-item  prop="phoneNum">
                                 <el-select
                                    v-model="optionalForm.boundUser"
                                    :remote-method="selectUser"
                                    :disabled="optionalForm.radioChecked == 1"
                                    placeholder="工号搜索"
                                    style="width:100%"
                                    filterable
                                    multiple
                                    remote
                                >
                                    <el-option
                                        v-for="item in users"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
            </el-form>
        </edu-dialog>
        <edu-dialog
            ref="orderDialog"
            :title="$t('排序')"
            :auto-height="true"
            size="small"
            class="systemDialog"
            @confirm="updateOrder"
        >
            <!-- 原版 -->
            <div class="edu-page-title">{{ currentMenuTypeName }}</div>
            <el-tree
                :data="orderMenuTree"
                :props="defaultProps"
                :expand-on-click-node="false"
                draggable
            />
        </edu-dialog>
        <el-dialog
            v-drag-dialog
            title="组内用户明细"
            :visible.sync="showUserGroupDialog"
        >
            <edu-table
                :total="queryUserForm.total"
                @page-change="pageChangeDialog"
                :data="usersUnderGroup"
                :selection="false"
            >
                <el-table-column label="账号">
                    <template slot-scope="scope">
                        {{ scope.row.studentId }}
                    </template>
                </el-table-column>
                <el-table-column label="用户名">
                    <template slot-scope="scope">{{ scope.row.name }}</template>
                </el-table-column>
                <el-table-column label="联系电话">
                    <template slot-scope="scope">
                        {{ scope.row.phoneNumber }}
                    </template>
                </el-table-column>
                <el-table-column label="联系邮箱" min-width="150">
                    <template slot-scope="scope">
                        {{ scope.row.email }}
                    </template>
                </el-table-column>
                <el-table-column label="类型">
                    <template slot-scope="scope">
                        {{
                            scope.row.userType == "1"
                                ? "老师"
                                : scope.row.userType == "2"
                                ? "学生"
                                : "本地用户"
                        }}
                    </template>
                </el-table-column>
            </edu-table>
        </el-dialog>
    </div>
</template>

<script>
const defaultCreateForm = {
    authNameCh: 'all',
    authNameEn: '',
    parentAuthId: '',
    urlPath: '',
    authCode: '',
    type: '',
    orderNo: '',
    application: '',
    mgerDeptId: '',
    roleType: 1
}
import {
    getAuthorities,
    findMenuListPage,
    deleteAuthorityMenu,
    orderMenus,
    addAuthorityMenu,
    updateAuthorityMenu,
    findMeunById,
    findTopTenUserList,
    getUserInfoListByGroupId
} from 'common/src/api/user'
import {
    getGroupUserList
} from 'common/src/api/public/information'
import UTILS from 'common/src/utils/utils'
// import { updateAuthorityMenu } from "common/src/api/session";

export default {
    name: 'Menus',
    filters: {
        menuType: function(value) {
            if (!value) {
                return ''
            }
            value = value.toString()
            return value == '1' ? '菜单' : '按钮'
        }
    },
    data() {
        var validateMenuName = (rule, value, callback) => {
            var regex = /^[\w\d\s\S\u4e00-\u9fa5]{1,255}$/
            if (regex.test(value)) {
                callback()
            } else {
                callback(
                    new Error(
                        UTILS.i18nReplace(this.$t('system.errorTipInfo'), {
                            minLength: 1,
                            maxLength: 255
                        })
                    )
                )
            }
        }
        return {
            queryMenuForm: {
                // authNameCh: "",
                name: '', // 修改bug2002（同后台沟通传参不对修改authNameCh改为name）
                total: 0,
                pageNum_: 1,
                pageSize_: 20,
                roleType: 1
            },
            type: '',
            typeList: [{ value: 1 }, { value: 2 }],
            parentMgerDeptId: '',
            departmentIsDisabled: false,
            departmentList: [
                {
                    name: '···',
                    value: '0'
                },
                {
                    name: '本科生',
                    value: '1'
                },
                {
                    name: '研究生',
                    value: '2'
                }
            ],
            isEdit: false,
            dialogTitle: '',
            menuTree: [],
            orderMenuTree: [],
            currentMenuTypeName: '',
            allMenus: [],
            menus: [],
            pickedDepts: [],
            defaultProps: {
                children: 'children',
                label: 'authNameCh'
            },
            createMenuForm: UTILS.clone(defaultCreateForm),
            rules: {
                authNameCh: [
                    {
                        required: true,
                        message: '请输入菜单中文名称',
                        trigger: 'blur'
                    },
                ],
                isActive: [
                    {
                        required: true,
                        message: '请选择是否激活',
                        trigger: 'blur'
                    },
                ],
                phoneNum: [
                    {
                        validator: this.checkPhoneNumList,
                        trigger: 'blur'
                    },
                ]
            },
            menuTreeTypeOpt: {
                value: 1,
                data: [
                    {
                        name: '管理员',
                        value: 1
                    },
                    {
                        name: '教师',
                        value: 2
                    },
                    {
                        name: '学生',
                        value: 3
                    }
                ]
            },
            currentMenuType: 1,
            tableKey: 1,
            users:[],
            userGroups:[],
            optionalForm: {
                activeState: 2,// 1:是，2：否
                radioChecked:1,//默认选中 1：用户组 2：用户
                boundUser: [],
                boundGroupId:'',
                options: [
                    {
                        key: 2,
                        label: '否',
                        value: 2
                    },
                    {
                        key: 1,
                        label: '是',
                        value: 1
                    },
                ]
            },
            showUserGroupDialog:false,
            usersUnderGroup: [],//用户列表
            queryUserForm: {
                userName: "",
                pageNum_: 1,
                total: 0,
                pageSize_: 20,
                groupId: ""
            },
            activeStatus: {
                1: '已激活',
                2: '未激活'
            }
        }
    },
    watch: {
        'menuTreeTypeOpt.value'(newVal) {
            if (newVal) {
                if (newVal !== this.currentMenuType) {
                    // 切换角色菜单，改变key值，table表重新渲染
                    this.tableKey = new Date().getTime();
                    this.queryMenuForm = {
                        name: '',
                        total: 0,
                        pageNum_: 1,
                        pageSize_: 20,
                        roleType: 1
                    }
                    this.queryMenuForm.roleType = newVal
                    this.queryMenus()
                    this.currentMenuType = newVal
                }
            }
        }
    },
    created() {},
    mounted() {
        this.showMenuTree()
        this.queryMenus()
        this.selectUserGroups()
    },
    methods: {
        handleChangeRadio(){
          this.optionalForm.boundUser = []
          this.optionalForm.boundGroupId = ""
        },
        getLabelStr(str) {
            if (!str) {
                return ''
            } else {
                return str.length > 10 ? str.substring(0, 10).concat('...') : str
            }
        },
        nodeClick(data) {
            this.queryMenuForm.parentAuthId = data.authId
            this.queryMenus(true)
        },
        handleSizeChange(data) {
            this.queryMenuForm.pageSize_ = data.pageSize
            this.queryMenuForm.pageNum_ = data.pageNum
            this.queryMenus()
        },
        editMenu(authId) {
            findMeunById(authId).then(rsp => {
                if(rsp.code !== 200)return
                this.$refs.editDialog.open()
                this.createMenuForm = rsp.data;
                this.optionalForm.activeState = this.createMenuForm.activeState ? this.createMenuForm.activeState * 1 : 2;
                this.createMenuForm.boundGroupId ? this.optionalForm.radioChecked = 1:this.optionalForm.radioChecked = 2
                this.optionalForm.boundUser = this.createMenuForm.boundUser ? this.createMenuForm.boundUser.split(',') : [];
                this.optionalForm.boundGroupId = this.createMenuForm.boundGroupId?this.createMenuForm.boundGroupId+"" :"";
            })
        },
        queryMenus(reset) {
            if (reset) {
                this.queryMenuForm.pageNum_ = 1
                this.queryMenuForm.total = 0
            }
            findMenuListPage(this.queryMenuForm).then(res => {
                if (res.code === 200) {
                    this.menus = res.data.list.filter(item=>item.type !== 2)
                    this.queryMenuForm.total = res.data.total_
                }
            })
        },
        showMenuTree() {
            let getWardenMenuTree = getAuthorities({
                roleType: 1
            })
            let getTeacherMenuTree = getAuthorities({
                roleType: 2
            })
            let getStudentMenuTree = getAuthorities({
                roleType: 3
            })
            let menuTree = []
            Promise.all([getWardenMenuTree, getTeacherMenuTree, getStudentMenuTree]).then(res => {
                console.log(res)
                res.forEach(item => {
                    if (item.code === 200) {
                        menuTree.push(this.$utils.listToTree('authId', 'parentAuthId', item.data.filter(item=>item.type!=2)))
                        this.menuTree = menuTree.filter(item=>item.type !==2)
                    }
                })
            })
        },
        openOrderDialog() {
            let index = this.menuTreeTypeOpt.value - 1
            this.currentMenuTypeName = this.menuTreeTypeOpt.data[index].name
            this.orderMenuTree = UTILS.clone(this.menuTree[index])
            this.$refs.orderDialog.open()
        },
        updateOrder() {
            const result = []
            this.getAllMenu(this.orderMenuTree, result)
            orderMenus(result).then(() => {
                this.$message({ type: 'success', message: this.$t('message.saveSuccess') })
                this.$refs.orderDialog.close()
                this.showMenuTree()
                this.queryMenus()
            })
        },
        getAllMenu(list, result, parent) {
            list.forEach((element, index) => {
                const node = {
                    orderNo: index + 1,
                    authId: element.authId,
                    roleType: element.roleType
                }
                if (parent) {
                    node.parentAuthId = parent.authId
                }
                result.push(node)
                if (UTILS.isNotEmpty(element.children)) {
                    this.getAllMenu(element.children, result, element)
                }
            })
        },
        checkPhoneNumList(rule, value, callback) {
            let reg = /^[1][3,4,5,7,8][0-9]{9}$/;
            let errorMsg = '';
            if(value){
                value.split(',').forEach(item => {
                    if (!reg.test(item)) {
                        this.isError = true;
                        return callback(new Error("输入格式有误，请重新输入"));
                    }
                })
            }
            this.isError = false;
            return callback();
        },
        closeDialog() {
            this.optionalForm.activeState = 2;
            this.optionalForm.phoneNum = '';
            this.$refs.editDialog.close();
        },
        submitConfig() {
            if(this.isError) {
                return;
            }
            this.createMenuForm.activeState = this.optionalForm.activeState;
            this.createMenuForm.boundUser = this.optionalForm.boundUser+"";
            this.createMenuForm.boundGroupId = this.optionalForm.boundGroupId;

            updateAuthorityMenu(this.createMenuForm).then(({ code, data }) => {
                if (code != 200) return;
                this.queryMenuForm.roleType = this.createMenuForm.roleType
                this.queryMenus(true)
                this.showMenuTree()
            })
            this.$refs.editDialog.close();
            sessionStorage.setItem('isReset', true);
        },
        selectUserGroups(){
            getGroupUserList().then(res => {
                    if (res.code === 200) {
                        this.userGroups = res.data.map(item=>{
                            return {
                                value: item.groupId + '',
                                label: item.groupName
                            }
                        })
                        console.log(this.userGroups)
                    }
                })
        },
        selectUser(query) {
            if (!query) return
            const data = { userId: query }
            this.loading = true
            findTopTenUserList(data)
                .then(res => {
                    this.loading = false
                    if (res.code == 200) {
                        
                        this.users = this.transData(res.data)
                    } else throw res.code
                })
                .catch(error => {
                    this.loading = false
                    this.$message({
                        type: 'error',
                        message: '查询用户出错'
                    })
                })
        },
        transData(list) {
            return list.map((item, index, array) => {
                return {
                    label: item.userName + '(' + item.userId + ')',
                    value: item.userName + '(' + item.userId + ')'
                }
            })
        },
        showUserGroup(groupId = "") {
            this.$set(this.queryUserForm, "groupId", groupId);
            this.showUserGroupDialog = true;
            this.getUserInfoListByGroupId();
        },
         /**
         * params {groupId 用戶組ID}
         * 根据用户组iD 查询用户
         */
        async getUserInfoListByGroupId() {
            try {
                if (!this.queryUserForm.groupId) {
                    this.$message({
                        type: "error",
                        message: "查询出错, 请重试."
                    });
                    return;
                }
                let { code, data } = await getUserInfoListByGroupId(
                    this.queryUserForm
                );
                if (code == 200) {
                    this.usersUnderGroup = data ? data.list : [];
                    this.queryUserForm.total = data.total_;
                }
            } catch (err) {
                this.$message({
                    type: "error",
                    message: "查询出错, 请重试."
                });
            }
        },
        pageChangeDialog(val) {
            this.queryUserForm.pageSize_ = val.pageSize;
            this.queryUserForm.pageNum_ = val.pageNum;
            this.getUserInfoListByGroupId();
        }
    }
}
</script>

<style lang="scss" scoped>
.left-part-box,
.right-part-box {
    float: left;
    margin-right: 20px;
}
.left-part-box {
    width: 300px;
    .el-tree {
        min-height: 450px;
    }
}
.right-part-box {
    width: calc(96% - 300px);
    .el-card {
        width: 100%;
        min-height: 450px;
        display: inline-block;
    }
}
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 4px;
    color: #3f3f3f;
}
.item-title {
    display: block;
    width: 100%;
    height: 32px;
}
.tree-title {
    margin: 0;
    line-height: 28px;
    padding-left: 8px;
    .el-button {
        float: right;
        margin-right: 4px;
    }
}
.menus-collapse-wrap {
    padding-left: 8px;
    margin-bottom: 8px;
    background: #fff;
}
.pl-20 {
    padding-left: 20px;
}
.search-bar {
    padding: 16px 0;
}
.radio{
    padding: 8px 0;
}
</style>
